package com.lizhivscaomei.cleanduplicatefiles.cmd;

import com.lizhivscaomei.cleanduplicatefiles.CleanDuplicateFilesApplication;
import com.lizhivscaomei.cleanduplicatefiles.cmd.event.FileEvent;
import com.lizhivscaomei.cleanduplicatefiles.cmd.event.FileEventPublisher;
import com.lizhivscaomei.cleanduplicatefiles.cmd.pojo.Result;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.io.File;
import java.io.IOException;

@Component
public class FileTask {

    @Autowired
    FileEventPublisher fileEventPublisher;

    @Async
    public void dealFile(ConfigFile config, File file) {
        //计算MD5
        String md5 = null;
        try {
            long begin = System.currentTimeMillis();
            md5 = DigestUtils.md5DigestAsHex(FileUtils.openInputStream(file));
            System.out.println("file size(KB):" + file.getTotalSpace() / 1024 + ",time(second):" + (System.currentTimeMillis() - begin) / 1000);
            Result temp = config.getResultsTemp().get(md5);
            if (null == temp) {
                temp = new Result();
                temp.setMd5(md5);
                config.getResultsTemp().put(md5, temp);
            }
            temp.getAll().add(file.getAbsolutePath());
            config.getMatchFiles().put(file, true);
            FileEvent event = new FileEvent(this);
            event.setConfig(config);
            event.setFile(file);
            fileEventPublisher.publish(event);
        } catch (IOException e) {
//            e.printStackTrace();
        }
    }
}
